package Send2ME::Register;

use Dancer::Plugin::Captcha::SecurityImage;

use Dancer ':syntax';

use Send2ME::Magic::Magic;
use Send2ME::Dao::Auth;
use Send2ME::Dao::User;

use Digest::Perl::MD5 'md5_hex';

prefix '/register';

get '/' => sub {
	template 'register';
};

get '/captcha' => sub {
    create_captcha {
        new => {
		   width      => 100,
		   height     => 25,
		   thickness  => 4,
		   rndmax     => 5,
		   scramble   => 1,
		   send_ctobg => 1,
		   bgcolor    => '#009999',
		   gd_font  => 'giant',
        },
        create     => [ normal => 'blank' ],
        particle   => [ 100 ],
        out        => { force => 'jpeg' },
    };
};

post '/' => sub {
	my ($name, $login, $password, $captcha) = 
  		(params->{name}, params->{login}, params->{password}, params->{captcha});
  		
	$name = $login unless $name;  		
  		
	my $valid = validate_captcha $captcha;
	clear_captcha;
	
	if (!$valid) {
  		redirect '/register/?error=wrong-capthca';
  		return;
	} 
	
	if (!$login || !$password) {
  		redirect '/register/?error=fill-form';
  		return;
	} 
	
	if (length($login) < 3) {
		redirect '/register/?error=login-too-short';
		return;
	}
	
	if (!isAcceptable($login)) {
		redirect '/register/?error=login-invalid';
		return;
	}
	
	if (!isAcceptable($password)) {
		redirect '/register/?error=password-invalid';
		return;
	}
	
	if (!isLoginUnique($login)) {
		redirect '/register/?error=login-in-use';
		return;
	}
	
	createUser({
		recipient => $login,
		name => $name,
		password => md5_hex($password),
	});
	
	my $user = getUser({ name => $name });
	
	if ($user) {
		currentUser($user);
		redirect '/';	
		return;
	}
	
	template 'login_failed';
};

sub isLoginUnique {
	my $recipient = shift;
	return !getUser({  recipient => $recipient });
}

1;